//
//  YYEIntroduceViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2018/1/3.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYEIntroduceViewController.h"
#import "YYEIntrolFirstCell.h"
#import "YYEIntrolSecondCell.h"
#import "YYEIntrolThirdCell.h"
#import "YYEIntrolCommandCell.h"
#import "YYECourseIntroModel.h"
#import "NSStringExt.h"

@interface YYEIntroduceViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) YYEBaseTableView *tableView;
@property (nonatomic,strong) YYECourseIntroModel *introModel;
@property (nonatomic,strong) NSMutableArray *datas;
@property (nonatomic,assign) NSInteger page;

@end

@implementation YYEIntroduceViewController

static NSString * titleCell   = @"titleCell";
static NSString * introCell   = @"introlCell";
static NSString * teacherCell = @"teacherCell";
static NSString * commandCell = @"commandCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.view.backgroundColor = [UIColor redColor];
    
    // 介绍
    [self configUI];
    
    [self loadData];
    
    
    // 评论数据
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //    [header beginRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = header;
    
    
    // 上拉刷新
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self loadMoreData];
    }];
    
    [self loadNewData];

}

- (void)loadData {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token,
                          @"cid":self.cid
                          };
    [AFNHelper post:LessonIntrol parameters:dic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        if ([responseObject[@"status"] isEqual:@1]) {
            self.introModel = [YYECourseIntroModel mj_objectWithKeyValues:responseObject[@"data"]];
            [self.tableView reloadData];
            
            if (self.block) {
                self.block(_introModel);
            }
        }
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        
    }];
    
    
}


- (void)loadNewData {
    
    self.page = 1;
    [self loadDataWithPage:self.page];
    
}

- (void)loadMoreData {
    
    self.page ++;
    [self loadDataWithPage:self.page];
    
}

- (void)loadDataWithPage:(NSInteger)page {
    
    NSDictionary *dic = @{
                          @"cid":self.cid,
                          @"p":@(self.page),
                          @"size":@10,
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token
                          };
    [SVProgressHUD show];
    [AFNHelper post:LessonComments parameters:dic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        if (self.page == 1) {
            [self.datas removeAllObjects];
        }
        if ([responseObject[@"status"] isEqual:@1]) {
            
            NSArray *commandArr = [YYELessonCommandModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.datas addObjectsFromArray:commandArr];
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        NSInteger totalPage = [responseObject[@"total_page"] integerValue];
        
        if (totalPage == self.page) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        [SVProgressHUD showWithStatus:ShowError];
        [SVProgressHUD dismissWithDelay:0.5];
        
    }];
    
}

- (void)configUI {
    
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[YYEIntrolFirstCell class] forCellReuseIdentifier:titleCell];
    [self.tableView registerClass:[YYEIntrolSecondCell class] forCellReuseIdentifier:introCell];
    [self.tableView registerClass:[YYEIntrolThirdCell class] forCellReuseIdentifier:teacherCell];
    [self.tableView registerClass:[YYEIntrolCommandCell class] forCellReuseIdentifier:commandCell];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    
}

- (YYEBaseTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[YYEBaseTableView alloc]initwithDelegate:self];
//        _tableView.backgroundColor = [UIColor redColor];
    }
    return _tableView;
    
}

- (NSMutableArray *)datas {
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
    
}

#pragma mark -- UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
//    if ([LoginModel shareLogin].token.length > 0) {
//        return 3;
//    }else {
//        return 4;
//    }
    return 4;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 3) {
        //            return 2;
        return self.datas.count;
        
    }else {
        return 1;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        YYEIntrolFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:titleCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.introModel;
        
        return cell;
        
    }else if (indexPath.section == 1) {
        
        YYEIntrolSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:introCell];
     
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.introModel;
        
        return cell;
        
    }else if (indexPath.section == 2) {
        
        YYEIntrolThirdCell *cell = [tableView dequeueReusableCellWithIdentifier:teacherCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.introModel;
        
        return cell;
        
    }else {
        
        YYEIntrolCommandCell *cell = [tableView dequeueReusableCellWithIdentifier:commandCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.commandModel = self.datas[indexPath.row];

        return cell;
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 84   66    128.5   73
    if (indexPath.section == 0) {
        return 84;
    }else if (indexPath.section == 1) {
        
        
        CGSize size = [self.introModel.intro boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 36, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
        return (10 + size.height + 33);
//        return 66;
    }else if (indexPath.section == 2) {
        
        
        CGSize size = [self.introModel.tintro boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 36, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
        return (81 + size.height + 20);
//        return 133.5;
    }else {
//        return 91;
        YYELessonCommandModel *model = self.datas[indexPath.row];
        
        CGSize sizeForLabel = [model.comment boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 36, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
        return sizeForLabel.height + 55;

    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    contentView.backgroundColor = GeneralBackColor;
    
    UIImageView *backIV = [[UIImageView alloc]init];
    backIV.image = [UIImage imageNamed:@"topBorder"];
    [contentView addSubview:backIV];
    
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.font = [UIFont systemFontOfSize:14];
    [backIV addSubview:nameLabel];
    
    [backIV makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsMake(0, 8, 0, 8));
    }];
    
    [nameLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backIV.left).offset(10);
        make.centerY.equalTo(backIV.centerY);
    }];
    
    if (section == 0) {
        
    }else if (section == 1) {
        
        nameLabel.text = @"课程介绍";
        
    }else if (section == 2) {
        
        nameLabel.text = @"任课教师";
        
    }else {
        
        nameLabel.text = @"评论";
        
    }
    
    return contentView;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0.01;
    }else {
        
        if (section == 3) {
            
            if (self.datas.count == 0) {
                
                return 0;

            }
            
        }
        return 40;

    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
